package com.miracle.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.miracle.entity.User;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jie.xi
 * @date 2022年05月18日 16:14
 */

public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)){
            //1.判断是否是POST请求
            if (!request.getMethod().equals("POST")) {
                throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
            }
            Map<String,String> map = new HashMap<>();
            ObjectMapper objectMapper = new ObjectMapper();
            try(InputStream inputStream = request.getInputStream()) {
                map = objectMapper.readValue(inputStream, Map.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if(map!=null){
                String username = map.get("username");
                String password = map.get("password");
                if(username == null){
                    username = "";
                }
                if(password == null){
                    password = "";
                }
                username = username.trim();
                password = password.trim();
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                this.setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
            return null;
        }
        return super.attemptAuthentication(request, response);
    }
}
